package ua.com.alus.resvac.crm.util;

import org.apache.log4j.Logger;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Encription utils
 * <p/>
 * Created by Usatov Alexey
 */
public class EncriptionUtils {
    private static final Logger LOGGER = Logger.getLogger(EncriptionUtils.class);
    private static final String MD5 = "MD5";
    private static final String MD5_HEX_FORMAT = "%1$032X";

    /**
     * Create 32 byte string that represent md5 hash for given password
     *
     * @param pass password
     * @return 32 byte string
     */
    public static String convertPasswordToMD5(String pass) {
        String result = "";
        try {
            MessageDigest m = MessageDigest.getInstance(MD5);
            byte[] data = pass.getBytes();
            m.update(data, 0, data.length);
            BigInteger i = new BigInteger(1, m.digest());
            result = String.format(MD5_HEX_FORMAT, i).toLowerCase();
        } catch (NoSuchAlgorithmException nsa) {
            LOGGER.error(nsa);
        }
        return result;
    }
}
